// pages/myself/order/OrderDetails.js
var Zan = require('../../../dist/index.js');
let WxNotificationCenter = require('../../../utils/WxNotificationCenter.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    orderId: "",
    order: null,
    customStore: "",
    store: '',
    storeId: app.globalData.storeId,
    orderDate: 0,
    payDate: 0,
    payMonyDate: 0,
    hideStatus: true,
    flag: 0,
    allPrice: 0,
    Countdown:'',
    logistics:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    this.setData({
      orderId: options.orderId,
      store: app.globalData.store
    })
    // 注册列表刷新事件
    WxNotificationCenter.addNotification("orderDetailRefreshNotification", this.refreshNotification, this);
    this.onPullDownRefresh();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    WxNotificationCenter.removeNotification("orderDetailRefreshNotification", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    console.log("============刷新==============");
    network._post_json(this, api.getOrderDetails, { orderId: this.data.orderId }, success);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  refreshNotification:function(){
    this.onPullDownRefresh();
  },
  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },

  copy: function (e) {
    var data = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: data,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            console.log(res.data) // data
          }
        })
      }
    })
  },

  // 取消订单
  cancel: function (e) {
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定取消该订单吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          network._post_json(that, api.delOrder, { id: that.data.orderId }, cancelSuccess);

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  cancel01: function (e) {
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定删除该订单吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          network._post_json(that, api.delOrder, { id: that.data.orderId }, cancelSuccess);

        } else if (res.cancel) {
          console.log('用户点击删除')
        }
      }
    })
  },
  //取消订单售后申请
  cancelrefund: function (e) {
    var product = e.currentTarget.dataset.product;
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定取消售后申请吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          network._post_json(that, api.cancelrefund, { orderNO: that.data.order.orderNO, productId: product.productId }, cancelrefundSuccess);

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  orderDialog:function(e){
    this.setData({
      orderDialog: !this.data.orderDialog
    })
  },
  /**
  * 查看物流 0=物流配送  1=自行配送 2=达达配送 3=到店自取',
  */
  goLogistics: function (e) {

    this.setData({
      logistics: null
    })
    if (this.data.order.deliverMethod == 0) {

      network._post_json(this, api.logistics, { ShipperCode: this.data.order.expressName, LogisticCode: this.data.order.expressNo, orderNO: this.data.order.orderNO }, logisticsSuccess);

    } else if (this.data.order.deliverMethod == 1) {



    } else if (this.data.order.deliverMethod == 2) {

      network._post_json(this, api.dada, { id: "b5b36477b73c43713b0e66b189d296e2" }, dadaSuccess);

    } else {

    }

    this.setData({
      orderDialog: !this.data.orderDialog
    })
  },

  // 确认收货
  endOrder: function (e) {
    network._post_json(this, api.endOrder, { id: this.data.orderId }, endSuccess);
  },
  //再来一单

  // 立即支付
  pay: function (e) {
    let order = {};
    order.orderId = this.data.order.id;
    order.orderNO = this.data.order.orderNO;
    if (this.data.order.oldMemberPrice != "0") {
      order.couponPrice = parseInt(this.data.order.oldMemberPrice);
      order.totalPrice = parseInt(this.data.order.total) + parseInt(this.data.order.oldMemberPrice);
    } else if (this.data.order.oldSaleMoney != "0") {
      order.couponPrice = parseInt(this.data.order.oldSaleMoney);
      order.totalPrice = parseInt(this.data.order.total) + parseInt(this.data.order.oldSaleMoney);
    } else {
      order.couponPrice = 0;
      order.totalPrice = this.data.order.total;
    }
    // console.log(order);
    wx.navigateTo({
      url: '/pages/pay/ChoosePay?order=' + JSON.stringify(order) + '&store=' + encodeURIComponent(JSON.stringify(this.data.store))
    })

  },

  /**
  * 拨打电话
  */
  call: function (e) {
    /**
    * 获取商家电话
    */
    if (app.globalData.store) {
      wx.makePhoneCall({
        phoneNumber: app.globalData.store.phone
      })
    }
  },
  /**
  * 联系配送
  */
  Courier: function (e) {
    if (this.data.order.deliverUserPhone) {
      wx.makePhoneCall({
        phoneNumber: this.data.order.deliverUserPhone
      })
    }
  },
  //售后
  shouhouTk: function (e) {
    shouhouTk(1, e);
  },

  scan: function (e) {
    var orderId = this.data.order.id;
    // 只允许从相机扫码
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        console.log(res);
        if (res.path) {
          let scene = decodeURIComponent(res.path);
          let index = scene.indexOf('scene=');
          if (index == -1) {
            this.showZanTopTips(this.error, '无效门店二维码！');
          } else {
            var scene = decodeURIComponent(res.path);
            var index = scene.indexOf('scene=')
            network._post_json(this, api.end, { orderId: orderId, storeId: scene.substring(index + 6, scene.length) }, scanSuccess);
          }

        } else if (res.result == "") {
          this.showZanTopTips(this.error, '无效门店二维码！');
        } else if (res.result == "*") {
          this.showZanTopTips(this.error, '无效门店二维码！');
        } else {
          this.showZanTopTips(this.error, '无效门店二维码！');
        }
      }
    })
  },


  // take: function (e) {
  //   var orderId = e.currentTarget.dataset.id;
  //   network._post_json(this, api.end, { orderId: orderId, storeId: this.data.storeId }, endSuccess);
  // }
}))
// 获取订单物流结果
var logisticsSuccess = function (that, res) {
  if (res.data.data) {
    let logistics = [];
    for (let i = res.data.data.Traces.length - 1; i >= 0; i--) {
      logistics.push(res.data.data.Traces[i]);
    }
    that.setData({
      logistics: logistics
    })
  }
}
//达达
var dadaSuccess = function(that,res){
  if (res.data.data) {
    let logistics = [];
    for (let i = 0; i < res.data.data.length; i++) {
      logistics.push(res.data.data[i]);
    }
    that.setData({
      logistics: logistics
    })
  }
}
// 获取订单详情结果
var success = function (that, res) {
  if (res.data.data) {
    if (res.data.data.writeoff_time){
      res.data.data.writeoff_time = utils.formatDate(new Date(res.data.data.writeoff_time))
    }
    that.setData({
      order: res.data.data
    })
    // res.data.data[j].products = products;
    // if (res.data.data.subscribeDate) {
    //   let time = ['上午', '下午', '晚上'];
    //   res.data.data.subscribeDate = utils.formatDate02(new Date(res.data.data.subscribeDate)) + ' ' + time[res.data.data.dateLink];
    // }
    // if (res.data.data.deliverDate != null) {
    //   res.data.data.deliverDate = utils.formatDate(new Date(res.data.data.deliverDate))
    // }
    // if (res.data.data.customStoreId) {
    //   network._post_json(that, api.storeDetails, { customStoreId: res.data.data.customStoreId }, storeDetailSuccess);
    // }
    // that.setData({
    //   order: res.data.data,
    //   orderDate: utils.formatDate(new Date(res.data.data.orderDate)),
    //   payDate: res.data.data.linkType == 2 ? utils.formatDate(new Date(res.data.data.orderDate)) : utils.formatDate(new Date(res.data.data.payDate)),
    //   payMonyDate: res.data.data.linkType == 2 ? utils.formatDate(new Date(res.data.data.creatDate)) : utils.formatDate(new Date(res.data.data.payMoneyDate)),
    // })

    // getTotal(that, res.data.data.product);
  }
}

var storeDetailSuccess = function (that, res) {
  if (res.data.data) {
    that.setData({
      customStore: res.data.data
    })

  }
}

var cancelSuccess = function (that, res) {
  //获取页面栈
  var pages = getCurrentPages();
  if (pages.length > 1) {
    //上一个页面实例对象
    var prePage = pages[pages.length - 2];
    prePage.onPullDownRefresh();
  }
  wx.navigateBack();
}
// 取消订单
var delSuccess = function (that, res) {
  that.showZanToast('订单取消成功');
  //获取页面栈
  var pages = getCurrentPages();
  if (pages.length > 1) {
    //上一个页面实例对象
    var prePage = pages[pages.length - 2];
    if (prePage.refresh && typeof (prePage.refresh) == "function") {
      prePage.refresh();
    }
  }
  setTimeout(function () {
    wx.navigateBack({

    })
  }, 2000)
}

// 完成订单
var endSuccess = function (that, res) {
  // if (res.data.data) {
  that.showZanToast('收货成功');
  var pages = getCurrentPages();
  if (pages.length > 1) {
    //上一个页面实例对象
    var prePage = pages[pages.length - 2];
    if (prePage.refresh && typeof (prePage.refresh) == "function") {
      prePage.refresh();
    }
  }
  setTimeout(function () {
    wx.navigateBack({

    })
  }, 2000)
  // }
}
//扫码成功
var scanSuccess = function (that, res) {
  that.showZanToast('确认消费成功');
  that.onPullDownRefresh();
  // that.data.order.status = 7
  // that.setData({
  //   order: that.data.order
  // })

  //获取页面栈
  var pages = getCurrentPages();
  if (pages.length > 1) {
    //上一个页面实例对象
    var prePage = pages[pages.length - 2];
    if (prePage.refresh && typeof (prePage.refresh) == "function") {
      prePage.refresh();
    }
  }
  setTimeout(function () {
    wx.navigateBack({

    })
  }, 2000)

}

/**
 * 商品总价
 */
var getTotal = function (that, items) {
  var price = 0;
  for (var i = 0; i < items.length; i++) {
    price += items[i].price * items[i].count
  }
  that.setData({
    allPrice: price
  })
  return price;
}

//售后
function shouhouTk(type, e) {

  var order = e.currentTarget.dataset.order;
  var product = e.currentTarget.dataset.product;
  // console.log('====================售后=====================');
  // console.log(order);
  // console.log(product);
  wx.setStorageSync('product', product);
  var linkType = e.currentTarget.dataset.order.linkType; //0=普通订单  1=拼团  2=积分换购 0,1，退钱  2，退积分 
  // var tktype = e.currentTarget.dataset.tktype; // 0=退款；1=退货退款
  wx.redirectTo({
    url: '/pages/myself/order/shouhou/tuikuan?orderId=' + order.id + '&productId=' + product.productId + '&linkType=' + order.linkType
  })

}
//取消售后申请
var cancelrefundSuccess = function (that, res) {
  console.log(res);
  that.showZanToast('取消售后申请成功');
  that.onPullDownRefresh();
  //获取页面栈
  var pages = getCurrentPages();
  if (pages.length > 1) {
    //上一个页面实例对象
    var prePage = pages[pages.length - 2];
    if (prePage.refresh && typeof (prePage.refresh) == "function") {
      prePage.refresh();
    }
  }
  setTimeout(function () {
    wx.navigateBack({

    })
  }, 2000)

}